package com.szl.yeb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szl.yeb.common.R;
import com.szl.yeb.dto.AdminPasswordInfo;
import com.szl.yeb.dto.LoginInfo;
import com.szl.yeb.exception.CustomException;
import com.szl.yeb.mapper.AdminMapper;
import com.szl.yeb.entity.Admin;
import com.szl.yeb.service.AdminService;
import com.szl.yeb.utils.AdminUtil;
import com.szl.yeb.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.szl.yeb.common.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szl.yeb.utils.MybatisPlusUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息(Admin)表服务实现类
 *
 * @author szl
 * @since 2022-08-24 16:21:21
 */
@Service("adminService")
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public PageResult getPage(Integer currentPage, Integer size, Admin admin) {
        Page<Admin> page = new Page<>(currentPage, size);

        QueryWrapper<Admin> queryWrapper = MybatisPlusUtil.queryWrapperBuilder(admin);

        this.page(page, queryWrapper);

        return new PageResult((int) page.getTotal(), page.getRecords());
    }

    @Override
    public R<Object> login(LoginInfo loginInfo, HttpServletRequest request) {

        String captcha = (String) request.getSession().getAttribute("captcha");
        if (captcha == null) {
            return R.errMsg("验证码失效，请重新获取");
        }
        if (!captcha.equals(loginInfo.getCode())) {
            return R.errMsg("验证码错误");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(loginInfo.getUsername());

        if (userDetails == null || !passwordEncoder.matches(loginInfo.getPassword(), userDetails.getPassword())) {
            return R.errMsg("用户名或密码错误");
        }

        if (!userDetails.isEnabled()) {
            return R.errMsg("帐号被禁用,请联系管理员");
        }

        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", jwtTokenUtil.generateToken(userDetails));

        return R.success("登录成功", tokenMap);

    }

    @Override
    public R<Object> getAdminInfo() {
        return null;
    }

    @Override
    public Admin getAdminByUsername(String username) {
        return baseMapper.selectOne(MybatisPlusUtil.getLQWrapper(Admin.class).eq(Admin::getUsername, username));
    }

    @Override
    public List<Admin> selectOtherAdminsWithRoles(String keyword) {
        return adminMapper.selectOtherAdminsWithRoles(keyword, AdminUtil.getCurrentAdmin().getId());
    }

    @Override
    public Boolean updateCurrentAdminOnPassword(AdminPasswordInfo adminPasswordInfo) {

        Admin currentAdmin = AdminUtil.getCurrentAdmin();

        String currentAdminPassword = currentAdmin.getPassword();
        String oldPassword = adminPasswordInfo.getOldPassword();
        String newPassword = adminPasswordInfo.getNewPassword();
        if (StringUtils.isEmpty(oldPassword)) {
            throw new CustomException("旧密码不能为空");
        }

        if (StringUtils.isEmpty(newPassword)) {
            throw new CustomException("新密码不能为空");
        }

        if (!newPassword.equals(adminPasswordInfo.getCheckNewPassword())) {
            throw new CustomException("两次提交的新密码不一致");
        }

        if (!passwordEncoder.matches(oldPassword, currentAdminPassword)) {
            throw new CustomException("旧密码校验失败");
        }

        newPassword = passwordEncoder.encode(newPassword);
        currentAdmin.setPassword(newPassword);
        this.updateById(currentAdmin);


        return true;

    }

    @Override
    public Boolean updateCurrentAdminOnUserFace(String url, Authentication authentication, HttpServletResponse response) {

        try {
            Admin currentAdmin = AdminUtil.getCurrentAdmin();
            currentAdmin.setUserFace(url);

            boolean b = this.updateById(currentAdmin);

            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(currentAdmin, null, authentication.getAuthorities()));
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            throw new CustomException("上传失败");
        }

        return true;
    }
}

